<?php
/**
 * Users Controller
 * 
 * @author CRIA Groep 1 <project@markvink.nl>
 * @version 1.0
 * @package controllers
 */
class UsersController extends AppController {
	/**
    * @var string Controller name (faster in PHP 4)
    */
	var $name = 'Users';
	
	/**
    * @var string Scaffolding on prefix 
    */	
	var $scaffold = 'admin';
	
	/**
	 * Callback function beforeFilter
	 * 
	 * Get triggered after init.
	 */
	function beforeFilter() {
		parent::beforeFilter(); 
		$this->Auth->allowedActions = array('login', 'logout', 'register', 'password', 'forgot');
		$this->Auth->userScope = array('User.password <>' => null);
		$this->Auth->fields = array(
			'username' => 'email',
			'password' => 'password',
		);
		
		if(!empty($this->params['prefix']) && $this->params['prefix'] == 'admin') {
			unset($this->User->validate['password']);
		}
	}
	
	/**
	 * Callback function _beforeScaffold
	 * 
	 * Get triggered on init Scaffold.
	 */
	function _beforeScaffold() {
		if(!empty($this->params['prefix']) && $this->params['prefix'] == 'admin') {
			unset($this->viewVars['associations']['hasOne']);
			unset($this->viewVars['scaffoldFields'][1]);
			if(in_array($this->action, array('edit', 'add'))) {
				unset($this->viewVars['scaffoldFields'][5]);
				$this->viewVars['scaffoldFields']['role'] = array('label' => 'Role', 'type' => 'select', 'options' => array('user' => 'User', 'admin' => 'Admin'), 'value' => $this->data['User']['role']);
			}
		}
		return true;
	}

	/**
	 * Callback function _afterScaffoldSave
	 * 
	 * Get triggered after savind by Scaffold.
	 * @param string $method add/edit
	 */
	function _afterScaffoldSave($method) {
		if($method == 'add') {
			$this->User->Password->save(array('Password' => array('user_id' => $this->User->id)));
			$this->__sendRegisterMail($this->User->read(), $this->User->Password->id);
		}
		return true;
	}
	
	/**
	 * Function login
	 * 
	 * Controller action
	 */
	function login() {
	}
	
	/**
	 * Function admin_login
	 * 
	 * Controller action, only accessible by admin prefix
	 */
	function admin_login() {
	}
	
	/**
	 * Function logout
	 * 
	 * Controller action
	 */
	function logout() {
		$this->redirect($this->Auth->logout());
	}
	
	/**
	 * Function admin_logout
	 * 
	 * Controller action, only accessible by admin prefix
	 */
	function admin_logout() {
		$this->redirect($this->Auth->logout());
	}
		
	/**
	 * Private function __add
	 * 
	 * Add a user
	 * @param array $data data array
	 */	
	function __add($data = array()) {   
		$this->User->create();	
		$this->User->set($data);
		if($this->User->validates(array('fieldList' => array('name', 'email')))) {   
			if($this->User->save($data, false)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Function register
	 * 
	 * Controller action
	 */
	function register() {
		if(!empty($this->data)) {
			if($this->__add($this->data)) {
				$this->User->Password->save(array('Password' => array('user_id' => $this->User->id)));
				
				$this->__sendRegisterMail($this->User->read(), $this->User->Password->id);
				$this->Session->setFlash("You will recieve a email for setting your password.");            
				$this->redirect('/');
			}
		}
	}

	/**
	 * Function password
	 * 
	 * Controller action
	 * @param UUID $key identifier
	 */
	function password($key = null) {
		$user = $this->__getUser($key);
		if(!empty($this->data)) {        
			$this->User->id = $user['User']['id'];
			$this->User->set($this->data);
			if($this->data['User']['password'] != $this->data['User']['confirm']) {
				$this->User->invalidate('confirm', 'Confirm don\'t match password');
			}
			if($this->User->validates( array('fieldList' => array('password') ) ) ) {
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
				if($this->User->save($this->data, false)) {
					$this->__deletePassword($key);
					if(!$this->Auth->user()) {
						$this->Auth->login($user);
					}
					$this->Session->setFlash("Password has been saved.");            
					$this->redirect('/');
				}
			}
		}
		$this->set(compact('user'));
	}
	
	/**
	 * Private function __getUser
	 * 
	 * Get the user by password key
	 * @param UUID $key identifier
	 */
	function __getUser($key = null) {
		$this->User->Password->id = $key;
		$user = is_array($this->User->Password->read()) ? $this->User->Password->read() : $this->Auth->user();
		if(!$user) {
			$this->Session->setFlash("Wrong parameters.");            
			$this->redirect('/');
		} 
		return $user;
	}
	
	/**
	 * Function edit
	 * 
	 * Controller action
	 */
	function edit(){
		if($this->data){
			$this->User->set($this->data);
			$this->User->id = $this->Auth->user('id');
			
			if($this->User->validates(array('fieldList' => array('name', 'email')))){	
				if ($this->User->save($this->data, array('validate' => false))){
					$this->Auth->login(SET::merge($this->Auth->user(), $this->User->read('password', $this->Auth->user('id'))));
					
					$this->Session->setFlash('Your profile has been updated.');
					$this->redirect( array('controller' => 'users', 'action' => 'edit') );
				}
			}
		} else {
			$this->data = $this->User->read(null, $this->Auth->user('id'));
		}
	}
	
	/**
	 * Private function __deletePAssword
	 * 
	 * Delete the password key
	 * @param UUID $key identifier
	 */
	function __deletePassword($key = null) {
		if(!is_null($key)) {
			$this->User->Password->delete($key);
		}
	}
	
	/**
	 * Function forgot
	 * 
	 * Controller action
	 */
	function forgot() {
		if(!empty($this->data)) {
			$user = $this->User->findByEmail($this->data['User']['email']);
			if(!$user) {
				$this->User->invalidate('email', 'This email address does not exists.');
			} else {
				if(!$user['Password']['id']) {
					$this->User->Password->save(array('Password' => array('user_id' => $user['User']['id'])));
					$user['Password']['id'] = $this->User->Password->id;
				}
				$this->__sendForgotMail($user, $user['Password']['id']);
			}
		}
	}
	
	/**
	 * Private function __sendForgotMail
	 * 
	 * Sending mail to user.
	 * @param array $user send mail to this user.
	 * @param UUID $key password identifier
	 */
	function __sendForgotMail($user, $key) {
		$this->Email->to = $user['User']['email'];
		$this->Email->subject = 'Laundrywaste.eu - Password reset';
		$this->Email->template = 'forgot';
		$this->set(compact('user', 'key'));
		$this->Email->send();
		
		$this->Session->setFlash("You will recieve a email for resetting your password.");            
		$this->redirect('/');
	}
	
	/**
	 * Private function __sendRegisterMail
	 * 
	 * Sending mail to user.
	 * @param array $user send mail to this user.
	 * @param UUID $key password identifier
	 */
	function __sendRegisterMail($user, $key) {
		$this->Email->to = $user['User']['email'];
		$this->Email->subject = 'Laundrywaste.eu - New account';
		$this->Email->template = 'register';
		$this->set(compact('user', 'key'));
		$this->Email->send();
	}
	
	/**
	 * Function laundriesuser_view
	 * 
	 * Controller action, only accessible by laundry route
	 */
	function laundriesuser_add() {
		$laundry = $this->User->Laundry->read(null, $this->params['laundry']);
		$this->set(compact('laundry'));
		
		if(!empty($this->data)) {
			if($this->__add($this->data)) {
				$this->User->Laundry->habtmAdd('User', $this->params['laundry'], $this->User->id);
				$this->User->Password->save(array('Password' => array('user_id' => $this->User->id)));
				
				$this->__sendRegisterMail($this->User->read(), $this->User->Password->id);
				
				$this->Session->setFlash("User has been created.");            
				$this->redirect(array('controller' => 'users', 'action' => 'index', 'laundry' => $this->params['laundry']));
			}
		}
	}
	
	/**
	 * Function laundriesuser_index
	 * 
	 * Controller action, only accessible by laundry route
	 * @param integer $laundry identifier, passed by route settings
	 */
	function laundriesuser_index($laundry = null) {
		$showlaundries = 5;
		$users = $this->User->findByLaundryId($laundry);
		$data = $this->paginate('User', array(
			'User.id' => $users
		));
		$this->set(compact('data', 'showlaundries'));
	}
	
	/**
	 * Function laundriesuser_select
	 * 
	 * Controller action, only accessible by laundry route
	 * @param integer $laundry identifier, passed by route settings
	 */
	function laundriesuser_select($laundry = null) {
		$users = $this->User->find('list', array(
			'conditions' => array(
				'User.id' => $this->User->findLinkedUsersByUserId($this->Auth->user('id')),
				'User.id NOT' => array_merge($this->User->findByLaundryId($laundry), array(0)),
			)
		));
		$this->set(compact('users'));
		
		if(!empty($this->data)) {
			$this->User->Laundry->habtmAdd('User', $this->params['laundry'], $this->data['User']['user_id']);
			$this->Session->setFlash("User has been added to laundry.");            
			$this->redirect(array('controller' => 'users', 'action' => 'index', 'laundry' => $laundry));
		}
	}
	
	/**
	 * Function laundriesuser_delete
	 * 
	 * Controller action, only accessible by laundry route
	 * @param integer $laundry identifier, passed by route settings
	 * @param integer $user identifier
	 */
	function laundriesuser_delete($laundry = null, $user = null) {
		if($user == $this->Auth->user('id')) {
			$this->Session->setFlash("Can't delete your own access.");            
			$this->redirect(array('controller' => 'users', 'action' => 'index', 'laundry' => $laundry));
		}
		$this->User->Laundry->habtmDelete('User', $laundry, $user);
		$this->Session->setFlash("User access has been removed.");            
		$this->redirect(array('controller' => 'users', 'action' => 'index', 'laundry' => $laundry));
	}
	
	/**
	 * Function laundriesuser_view
	 * 
	 * Controller action, only accessible by laundry route
	 * @param integer $laundry identifier, passed by route settings
	 * @param integer $user identifier
	 */
	function laundriesuser_view($laundry = null, $user = null) {
		if(!in_array($user, $this->User->findLinkedUsersByUserId($this->Auth->user('id')))) {
		
			$this->Session->setFlash("You have no access for that user profile.");            
			$this->redirect(array('controller' => 'users', 'action' => 'index', 'laundry' => $laundry));
		}
		$this->data = $this->User->findById($user);
		$access = $this->User->Laundry->findByUserId($this->Auth->user('id'));
		$user = $this->User->read(null, $user);
		
		$this->set(compact('user', 'access'));
	}
	
	/**
	 * Function dashboard
	 * 
	 * Controller action
	 */
	function dashboard() {
		$this->render('/pages/dashboard');
	}
}